package 其他;


public class 求一个数的平方根精确到小数点后6位 {

    public static void main(String[] args) {
        System.out.println(sqrt(63,6 ));


    }

    public static double sqrt(double num,int n){
        int end = 8;
        int start = 0;
        while (end > start){
            int mid = start + (end - start + 1 >> 1);
            if (num > mid * mid){
                start = mid;
            }else if (num == mid * mid){
                return mid;
            }else {
                end = mid - 1;
            }
        }
        double res = start;
        for (int i = 1; i <= n + 1; i++) {
            end = 9;
            start = 0;
            while (end > start){
                int mid = start + (end - start + 1 >> 1);
                double res1 = res + mid * Math.pow(10, -i);
                if (num > res1 * res1){
                    start = mid;
                }else if (num == res1 * res1){
                    return res1;
                }else {
                    end = mid - 1;
                }
            }
            res += start * Math.pow(10, -i);
        }
        String resStr = res + "";
        char c = resStr.charAt(n+2);
        resStr = resStr.substring(0, n+2);
        if (c >= '5'){
            res = new Double(resStr) + 1*Math.pow(10, -n);
        }
        return res;
    }
}
